package com.why.pool;

import com.why.enums.ErrorEnum;
import com.why.exception.RpcException;
import com.why.handler.RequestHandler;
import com.why.message.RpcRequest;
import com.why.message.RpcResponse;
import com.why.provider.ServiceRegistry;
import lombok.extern.slf4j.Slf4j;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

@Slf4j
public class Worker implements Runnable {


    private Socket socket;
    private ServiceRegistry registry;

    public Worker(Socket socket, ServiceRegistry registry) {
        this.registry = registry;
        this.socket = socket;
    }


    @Override
    public void run() {
        log.info("线程{}开始处理任务...", Thread.currentThread().getName());

        try {

            ObjectInputStream InputStream = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            log.info("得到输入输出流,开始调用Requesthandler执行方法");

            RpcRequest rpc = (RpcRequest) InputStream.readObject();
            String interfaceName = rpc.getInterfaceName();
            Object service = registry.getRegisterService(interfaceName);
            log.info("线程{}获取到服务{}", Thread.currentThread().getName(), service);
            Object result = RequestHandler.handler(service, rpc);
            log.info("调用成功!返回响应结果{}...", result);
            outputStream.writeObject(RpcResponse.isSuccess(result));
            outputStream.flush();

        } catch (Exception e) {

            log.error("线程在处理请求的时候发生了一些问题....", e);
            throw new RpcException(ErrorEnum.NOT_FOUND);
        }


    }
}